from lviewer.util import events
import os
import _warnings
import hashlib

def build_status(folder):
    hash = hashlib.new('md5')

    result = []
    for dirpath, dirnames, filenames in os.walk(folder):
        pieces = dirnames + filenames
        for dirname in dirnames:
            hash.update(dirname)
        for filename in filenames:
            fullpath = os.path.join(dirpath, filename) 
            data = os.stat(fullpath)
            hash.update(fullpath)
            hash.update(repr(data))

    return hash.digest()

class BasicFileChangeMonitor( object ):
    def __init__(self, folder):
        self.folder = folder

        self.on_change = events.Event()
        self.repeater = events.Repeater(.01, self.check_files)
        self.status = build_status(self.folder)

    def check_files(self):
        if not self.repeater.active:
            return
        new_status = build_status(self.folder)
        if new_status != self.status:
            self.status = new_status
            self.on_change.fire()

    def stop(self):
        self.on_change.cancel()
        self.repeater.stop()
